<template>
  <div class="base-wrap">
    <div class="content">
      <div class="base-title">菜单管理</div>
      <search
        show-export
        showAdd
        :data="searchData"
        @search-reset="reset"
        @search-submit="searchSubmit"
        @add="
          () => {
            dialogVisible = true
          }
        "
      />
      <com-table
        :columns="columns"
        :data="listData"
        :loading="loading"
        row-key="id"
        :index="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <template slot="status" slot-scope="{ row }">
          <el-switch
            :disabled="row.disabled"
            v-model="row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="val => statusChange(val, row)"
          />
        </template>
      </com-table>
      <!-- <el-pagination
        v-if="listData.length !== 0"
        :current-page.sync="defaultParams.pageNum"
        :page-sizes="pageSizes"
        :page-size="defaultParams.pageSize"
        class="com-table-pagination"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      /> -->
    </div>
    <el-dialog
      :title="`${dialogTitle}菜单`"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="25%"
      @close="closeDialog('ruleForm')"
    >
      <el-form ref="ruleForm" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" style="width: 90%" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单id" prop="id">
          <el-input
            :disabled="dialogTitle === '编辑'"
            v-model="form.id"
            placeholder="5位数id；一级菜单: 1xx00；二级: 1xxxx"
            maxlength="5"
            style="width: 90%"
            @input="routeChange"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="form.status"></el-switch>
        </el-form-item>
        <el-form-item label="是否一级菜单">
          <el-switch v-model="form.isFirstLevel" disabled></el-switch>
        </el-form-item>
        <el-form-item v-if="form.id.length === 5 && !form.isFirstLevel" label="父级菜单" prop="parentId">
          <el-select v-model="form.parentId" style="width: 90%">
            <el-option v-for="item in parentRouteList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单地址" prop="alias">
          <el-input v-model="form.alias" style="width: 90%" placeholder="一级菜单: /菜单地址；二级: 菜单地址" />
        </el-form-item>
        <el-form-item label="菜单介绍">
          <el-input v-model="form.description" type="textarea" placeholder="请输入菜单简介" style="width: 90%" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableMixins from '@mixins/table-mixins'
import { deepClone } from '@/utils'

const required = { required: true, message: '该项为必填项！' }
export default {
  name: 'Route',
  components: {},
  mixins: [tableMixins],
  data() {
    const checkId = async (rule, value, callback) => {
      if (String(value).length === 5 && this.dialogTitle === '新增') {
        const res = await this.$api.routeManage.checkId({ id: value })
        if (!res) {
          return callback(new Error('菜单id已存在'))
        }
      }
      if (String(value).length !== 5) {
        return callback(new Error('菜单id应为一个5位数'))
      }
      if (this.form.alias) {
        if (/^(1?[0-9]{2}?00)$/.test(value) && !/^\//.test(this.form.alias)) {
          // eslint-disable-next-line quotes
          return callback(new Error('一级菜单id应以00结尾'))
        }
        if (!/^(1?[0-9]{2}?00)$/.test(value) && /^\//.test(this.form.alias)) {
          // eslint-disable-next-line quotes
          return callback(new Error('非一级菜单应不应以00结尾'))
        }
        this.$refs.ruleForm.validateField('alias')
      }
    }
    const checkAlias = async (rule, value, callback) => {
      if (this.oldAlias !== value) {
        const res = await this.$api.routeManage.checkId({ alias: value })
        if (!res) {
          return callback(new Error('菜单地址已存在'))
        }
      }
      if (this.form.id) {
        if (/^(1?[0-9]{2}?00)$/.test(this.form.id) && !/^\//.test(value)) {
          // eslint-disable-next-line quotes
          return callback(new Error("一级菜单应以'/'开头"))
        }
        if (!/^(1?[0-9]{2}?00)$/.test(this.form.id) && /^\//.test(value)) {
          // eslint-disable-next-line quotes
          return callback(new Error("非一级菜单应不应以'/'开头"))
        }
        this.$refs.ruleForm.validateField('id')
      }
    }
    return {
      idExistence: false, // id是否存在
      oldAlias: '', // 旧地址
      columns: [
        { key: 'id', title: '菜单id' },
        { key: 'name', title: '菜单名称' },
        { key: 'alias', title: '菜单地址' },
        { key: 'createTime', title: '创建时间' },
        { key: 'status', title: '是否启用', slot: true },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          render: (h, params, index) => {
            return h('div', [
              h('el-button', {
                props: {
                  icon: 'el-icon-edit',
                  type: 'primary',
                  size: 'mini',
                  circle: true
                },
                attrs: { title: '编辑' },
                on: {
                  click: () => {
                    this.dialogVisible = true
                    this.getDet(params)
                  }
                }
              })
            ])
          }
        }
      ],
      searchData: [
        { type: 'input', field: 'name', label: '菜单名称', placeholder: '请输入菜单名称', clearable: true },
        { type: 'input', field: 'alias', label: '菜单地址', placeholder: '请输入菜单地址', clearable: true },
        {
          type: 'select',
          field: 'status',
          label: '是否启用',
          placeholder: '请选择状态名称',
          clearable: true,
          options: [
            { label: '全部', value: '' },
            { label: '是', value: '1' },
            { label: '否', value: '0' }
          ]
        }
      ],
      dialogVisible: false,
      dialogTitle: '新增',
      parentRouteList: [],
      form: {
        id: '',
        status: true
      },
      rules: {
        name: required,
        id: [required, { validator: checkId }],
        alias: [required, { validator: checkAlias }],
        status: required,
        parentId: required
      }
    }
  },
  filters: {},
  // 监听属性 类似于data概念
  computed: {},
  watch: {},
  created() {
    this.getdic()
  },
  mounted() {},
  // 方法集合
  methods: {
    // 新增弹窗关闭
    closeDialog(formName) {
      this.dialogTitle = '新增'
      this.dialogVisible = false
      this.form = {
        id: '',
        status: true
      }
      this.$refs[formName].resetFields()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.dialogTitle === '新增') {
            const res = await this.$api.routeManage.newRoute(this.form)
            if (res) this.$message.success('新增成功')
          } else {
            const res = await this.$api.routeManage.updateRoute(this.form)
            if (res) this.$message.success('修改成功')
          }
          this.getList()
          this.dialogVisible = false
        }
      })
    },
    async statusChange(value, row) {
      const res = await this.$api.routeManage.updateRoute(row)
      this.getList()
    },
    getDet(params) {
      this.dialogTitle = '编辑'
      this.oldAlias = params.alias
      params.isFirstLevel = /^(1?[0-9]{2}?00)$/.test(params.id)
      this.form = params
    },
    async getdic() {
      this.parentRouteList = (await this.$api.routeManage.list({ parentId: 0 })).list
    },
    async routeChange(id) {
      this.form.isFirstLevel = /^(1?[0-9]{2}?00)$/.test(id)
    }
  }
}
</script>
<style lang="less" scoped>
// @import url();
</style>
